var timerid=null;
var countdown_num = 0;
var countdown_total = 0;

var timerid='';            
var ajax = null;		
var pattern = "";
var server ="";
var service = "";
var hostname = "";
var downloaduri = "";
/*
chrome.extension.onConnect.addListener(function(port) {
	console.log('Content Stript is now listening...');
	port.onMessage.addListener(function(msg) {
		console.log('message '+msg.action+'arrived'+msg.data.toString());
		if (msg.action == "tick"){
			var perc = 100-parseInt(msg.data);
			tick(perc,100);
			return;
		}
	});
});
*/

function creatediv()
{
	var width = document.body.offsetWidth;
	var left = Math.round(((width-200)/width)*100).toString();
	var divbody = '<div id="ext-body" style="position:absolute;left:'+left+'%;top:5px;z-index:9999;width:200px;height:20px;cursor: pointer;text-align: left;font-family: sans-serif;font-size: 0.8em;margin-top: 2px;background: transparent;padding:2px 2px;"><div id="ext-processid" style="position:relative;width:150px;height:12px;border:1px solid #000000;"><span id="ext-bar" style="text-align:center;float:left;width:100%;height:12px;background-color:#FFFFFF;">Connecting...</span></div></div>';
	$('body').append(divbody);
}


chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
	var res = {status:'OK', data:null};
    if(request.action == 'download'){		
		if ($("#ext-body")[0]){
			reset();
			return;
		}	
		res.data={
			url:encodeURIComponent(document.URL),
			quality:0,
			lang :'pt-br',
			adblock : 0
		};
		creatediv();
		sendResponse(res);
		return;
    }
	else if(request.action == 'start'){
		downloaduri = request.data.downloaduri;
		countdown_num = request.data.countdown_num;
		countdown_total = request.data.countdown_total;
		$('#ext-body').css('text-align','left');
		timerid=window.setInterval("countdown()",100);
		sendResponse(res);
		return;
	}
	else if(request.action == 'reset'){
		reset();
		sendResponse(res);
		return;
	}
	else if(request.action == 'tick'){
		var uri = request.data.downloaduri;
		var perc = request.data.value;
		perc=100-parseInt(perc);
		tick(perc,100);
		if (perc==0 && uri != null){
			downloaduri = uri;
			save();
		}
		sendResponse(res);
		return;
	}
	else{
		res.status='KO';
		sendResponse(res);
	}
});

function tick(pos,total)
{
	var perc = Math.round(100-(pos/total*100));
	if (perc<0) return;
	var red   = (Math.round(255*(100-perc)/100)).toString(16);if (red.length<2) red='0'+red;
	var green = (Math.round(255*(perc/100))).toString(16);if (green.length<2) green='0'+green;
	var color = "#"+red+green+'00';
	var value = (perc).toFixed(0);
	$('#ext-bar').text('').css('background-color',color).css('width',value.toString()+'%');
}

function countdown(){
	if (countdown_num==countdown_total){
		$('#ext-bar').text('').css('width','0%');
	}
	countdown_num--;
	if (downloaduri==""){
		window.clearInterval(timerid);
		timerid='';
		return;
	}	
	if(countdown_num >= 0)	{ 
		tick(countdown_num,countdown_total);
	}
	else{ 
		if(timerid!=""){
			window.clearInterval(timerid);
			timerid='';
			save();						
		}		
	}	
}

function start(data)
{
	downloaduri = data.downloaduri;
	countdown_num = data.countdown_num;
	countdown_total = data.countdown_total;
	timerid=window.setInterval("countdown()",100);
}

function reset(){
	if(timerid!=""){
		window.clearInterval(timerid);
		timerid='';
	}
	downloaduri="";
	countdown_num=0;
	countdown_total=0;
	$('#ext-body').remove();
};

function save(){
	$('#ext-bar').css('text-align','center');
	$('#ext-bar').html('<a id="targetfile" style="text-decoration:none;" href="'+downloaduri+'" target="_blank">Download...</a>');
	$('body').append('<iframe src ="'+downloaduri+'" width="0" height="0"><a id="targetfile" href="'+downloaduri+'">Download</a></iframe>');		
	window.setTimeout("reset()",10000);
};